<script>
import { getFontFamily, getClassPrefix } from './util'

export default {
  name: 'UiIcon',
  functional: true,
  props: {
    name: {
      type: String
    },
    size: {
      type: String,
      default: '16px'
    },
    color: {
      type: String
    }
  },
  render(h, context) {
    const { props, data } = context
    const style = {}
    if (props.color) {
      style.color = props.color
    }
    const classPrefix = getClassPrefix() || ''
    let nextClass = ['ui-icon', getFontFamily()]
    const className = data.staticClass || data.class
    if (className) {
      if (Array.isArray(className)) {
        nextClass = nextClass.concat(className)
      } else {
        nextClass.push(className)
      }
    }
    if (props.name && props.name.indexOf('svg://') === 0) {
      const iconName = props.name.substr(6)
      if (props.size) {
        style.width = props.size
        style.height = props.size
      }
      return h('svg', {
        class: ['ui-icon--svg'].concat(nextClass),
        style,
        attrs: Object.assign({}, context.data.attrs, {
          'aria-hidden': 'true'
        }),
        on: {
          click(evt) {
            if (context.listeners.click) {
              context.listeners.click(evt)
            }
          }
        }
      }, [
        h('use', {
          attrs: {
            'xlink:href': `#icon-${iconName}`
          }
        })
      ])
    } else {
      if (props.size) {
        style['font-size'] = props.size
        style.width = props.size
        style.height = props.size
      }
      if (props.name) {
        nextClass.push(`${classPrefix}${props.name}`)
      }
      return h('span', {
        class: ['ui-icon--default'].concat(nextClass),
        style,
        attrs: context.data.attrs,
        on: {
          click (evt) {
            if (context.listeners.click) {
              context.listeners.click(evt)
            }
          }
        }
      }, context.slots().default)
    }
  }
}
</script>
<style lang="less">
.ui-icon.icon-loading{
  display: inline-block;
  &:before {
    display: inline-block;
    animation: ui-loading-rotating 1s linear infinite;
  }
}
@keyframes ui-loading-rotating{
  0% {
      transform: rotate(0);
  }
  100% {
      transform: rotate(1turn);
  }
}
.ui-icon--svg {
  display: inline-block;
}
.ui-icon--default {
  display: inline-block;
  vertical-align: top;
  > svg {
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
